<template>
    <div class="login-bg">
        <div class="flex-c absolute right-5 top-3">
            <el-dropdown trigger="click" style="color: #fff;">
                <GlobalizationIcon
                    class="internationalization w-[40px] h-[48px] p-[11px] cursor-pointer outline-hidden" />
                <template #dropdown>
                    <el-dropdown-menu class="translation">
                        <el-dropdown-item :style="getDropdownItemStyle(locale, 'zh')"
                            :class="['dark:text-white!', getDropdownItemClass(locale, 'zh')]" @click="translationCh">
                            <IconifyIconOffline v-show="locale === 'zh'" class="check-zh" :icon="Check" />
                            简体中文
                        </el-dropdown-item>
                        <el-dropdown-item :style="getDropdownItemStyle(locale, 'en')"
                            :class="['dark:text-white!', getDropdownItemClass(locale, 'en')]" @click="translationEn">
                            <span v-show="locale === 'en'" class="check-en">
                                <IconifyIconOffline :icon="Check" />
                            </span>
                            English
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
            <!-- 主题 -->
            <el-switch v-model="dataTheme" inline-prompt :active-icon="dayIcon" :inactive-icon="darkIcon"
                @change="dataThemeChange" />
        </div>

        <div class="login-form">
            <Motion>
                <h2 class="outline-none">{{ t("login.title") }}</h2>
            </Motion>

            <el-form ref="ruleFormRef" :model="ruleForm" :rules="loginRules" size="large">
                <Motion :delay="100">
                    <el-form-item
                        :rules="[{ required: true, message: t(`login.usernameVerification`), trigger: 'blur' }]"
                        prop="username">
                        <el-input clearable v-model="ruleForm.username" :placeholder='t(`login.username`)'
                            :prefix-icon="useRenderIcon(User)" />
                    </el-form-item>
                </Motion>

                <Motion :delay="150">
                    <el-form-item :rules="[{ required: true, message: t(`login.passwordVerifiers`), trigger: 'blur' }]"
                        prop="password">
                        <el-input clearable show-password v-model="ruleForm.password" :placeholder="t(`login.password`)"
                            :prefix-icon="useRenderIcon(Lock)" @keyup.enter="onLogin(ruleFormRef)" />
                    </el-form-item>
                </Motion>

                <!-- <Motion :delay="200">
                    <el-form-item prop="imageCode">
                        <el-input clearable v-model="ruleForm.imageCode" placeholder="验证码"
                            :prefix-icon="useRenderIcon(guideIcon)" style="width:63%" />
                        <div class="code">
                            <img :src="codeUrl" @click="getCode" />
                        </div>
                    </el-form-item>
                </Motion> -->

                <Motion :delay="250">
                    <el-button class="w-full mt-4" size="default" type="primary" :loading="loading"
                        @click="onLogin(ruleFormRef)">
                        {{ t("login.login") }}
                    </el-button>
                </Motion>
            </el-form>
        </div>

    </div>
</template>

<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount, computed } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import guideIcon from '@iconify-icons/ep/guide';
import Check from "@iconify-icons/ep/check";

import { useSettingStoreHook } from "@/store/modules/settings";
import { useNav as internationalization } from "@/layout/hooks/useNav";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import GlobalizationIcon from "@/assets/svg/globalization.svg?component";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const { locale, translationCh, translationEn } = useTranslationLang();
const {
    layout,
    device,
    logout,
    onPanel,
    pureApp,
    username,
    userAvatar,
    avatarsStyle,
    toggleSideBar,
    getDropdownItemStyle,
    getDropdownItemClass
} = internationalization();

defineOptions({
    name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const pureMap = useSettingStoreHook()

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title, apiurl } = useNav();

const ruleForm = reactive({
    username: "",
    password: "",
    imageCode: "",
    imageGuid: 0
});

// 定义登录函数
const onLogin = async (formEl: FormInstance | undefined) => {
    // 设置加载状态为true
    loading.value = true;
    // 如果表单元素不存在，则返回
    if (!formEl) return;
    // 验证表单
    await formEl.validate((valid, fields) => {
        // 如果验证通过
        if (valid) {
            // 调用登录函数
            useUserStoreHook()
                .loginByUsername(ruleForm)
                .then(res => {
                    // 设置加载状态为false
                    loading.value = false;
                    // 获取后端路由
                    //   console.log(res)
                    // 初始化路由
                    initRouter().then(() => {
                        // 跳转到顶部菜单
                        router.push(getTopMenu(true).path);
                        // 显示登录成功消息
                        message(t('login.loginSuccess'), { type: "success" });
                        // pureMap.audio.play()
                        // pureMap.audio.pause()
                    });
                }).catch(err => {
                    // 设置加载状态为false
                    loading.value = false;
                    // 获取验证码
                    getCode()
                    // 清空验证码
                    ruleForm.imageCode = ""
                });
        } else {
            // 设置加载状态为false
            loading.value = false;
            // 返回验证错误信息
            return fields;
        }
    });
};

// 定义获取验证码函数
const getCode = function () {
    // 生成新的验证码guid
    ruleForm.imageGuid = new Date().getTime();
}
// 调用获取验证码函数
getCode()

// 计算验证码图片地址
const codeUrl = computed(() => {
    return apiurl.value + "/api/VerifyCode/Generate/" + ruleForm.imageGuid
})

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
    if (code === "Enter") {
        onLogin(ruleFormRef.value);
    }
}

// 在组件挂载时，添加键盘按下事件监听器
onMounted(() => {
    window.document.addEventListener("keypress", onkeypress);
});

// 在组件卸载前，移除键盘按下事件监听器
onBeforeUnmount(() => {
    window.document.removeEventListener("keypress", onkeypress);
});
</script>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
    padding: 0;
}

.internationalization:focus,
.internationalization:active {
    outline: none !important;
    box-shadow: none !important;
}

.translation {
    ::v-deep(.el-dropdown-menu__item) {
        padding: 5px 40px;
    }

    .check-zh {
        position: absolute;
        left: 20px;
    }

    .check-en {
        position: absolute;
        left: 20px;
    }
}
</style>
